#include <string>
#include <gtest/gtest.h>
#include "jkutil/configparser.h"
using namespace std;
TEST(util, configparser)
{
    Util::ConfigParser parser("src/jkutil/test/jkbus.xml");
    ASSERT_TRUE(parser.is_valid());
    int val;
    std::string strVal;
    ASSERT_EQ(parser.get("Master.Simulate", val), 0);
    ASSERT_EQ(val, 1);

    ASSERT_EQ(parser.get("Master[0].name", strVal, true), 0);
    ASSERT_STREQ(strVal.c_str(), "CAN0");
    ASSERT_EQ(parser.get("Master[1].name", strVal, true), 0);
    ASSERT_STREQ(strVal.c_str(), "CAN1");

    ASSERT_EQ(parser.get("Master.Slave[2].enable", val, true), 0);
    ASSERT_EQ(val, 1);

    ASSERT_EQ(parser.set("Master.Simulate", 2), 0);
    ASSERT_EQ(parser.get("Master.Simulate", val), 0);
    ASSERT_EQ(val, 2);
    ASSERT_EQ(parser.set("Master.Simulate", 1), 0);
}

class XmlTest : public testing::Test
{
public:
    virtual void SetUp()
    {
        system("rm -f /tmp/extiocfg.xml");
        parser = new Util::ConfigParser("/tmp/extiocfg.xml");
    }
    virtual void TearDown() { delete parser; }

    Util::ConfigParser* parser;
};

TEST_F(XmlTest, xml_add_ele)
{
    ASSERT_FALSE(parser->is_valid());
    ASSERT_EQ(parser->create_file("ExtioSetup"), 0);
    ASSERT_TRUE(parser->is_valid());
    ASSERT_EQ(parser->add("Version", 2, true), 0);
    ASSERT_EQ(parser->add("ExtioCount", "2"), 0);
    ASSERT_EQ(parser->add("ExtioMod.Name", "a", true), 0);
    ASSERT_EQ(parser->add("ExtioMod.Comm.Type", "1", true), 0);
    ASSERT_EQ(parser->add("ExtioMod.Comm.Tcp.IP", "192.168.100.1", true), 0);
    ASSERT_EQ(parser->add("ExtioMod.Comm.Tcp.Port", "502", true), 0);
    ASSERT_EQ(parser->add("ExtioMod.Comm.Tcp.tcpSlaveID", "1", true), 0);
    ASSERT_EQ(parser->add("ExtioMod[1].Name", "a", true), 0);
    ASSERT_EQ(parser->add("ExtioMod[1].Comm.Type", "1", true), 0);
    ASSERT_EQ(parser->add("ExtioMod[1].Comm.Tcp.IP", "192.168.100.1", true), 0);
    ASSERT_EQ(parser->add("ExtioMod[1].Comm.Tcp.Port", "502", true), 0);
    ASSERT_EQ(parser->add("ExtioMod[1].Comm.Tcp.tcpSlaveID", "1", true), 0);
    ASSERT_EQ(parser->add("ExtioMod[3].Comm.Tcp.tcpSlaveID", "1", true), 0);

    auto p = Util::ConfigParser("/tmp/extiocfg.xml");
    string v;
    ASSERT_EQ(p.get("Version", v, true), 0);
    ASSERT_STREQ(v.c_str(), "2");
    ASSERT_EQ(p.get("ExtioCount", v), 0);
    ASSERT_STREQ(v.c_str(), "2");
    ASSERT_EQ(p.get("ExtioMod[3].Comm.Tcp.tcpSlaveID", v, true), 0);
    ASSERT_STREQ(v.c_str(), "1");
}